package com.lwisn.demo.presentation.listener;

import java.awt.FileDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.nio.charset.Charset;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.text.JTextComponent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.DecoratingClassLoader;

import com.lwisn.demo.decoding.FileDecoder;
import com.lwisn.demo.encoding.EncodingType;
import com.lwisn.demo.factory.FileEncoderFactory;
import com.lwisn.demo.logic.FileEncoder;
import com.lwisn.demo.logic.FileEncoderUtf8;

public class GuiListener implements ActionListener {
	
	private Logger logger = LoggerFactory.getLogger(GuiListener.class);
	
	private JTextArea textArea;
	private FileEncoder encoder;
	private FileDecoder decoder;
	private JComboBox comboBox;
	
	public GuiListener() {
		
	}

	public void setTextArea(JTextArea textArea) {
		this.textArea = textArea;
	}
	
	public void setComboBox(JComboBox comboBox) {
		this.comboBox = comboBox;
	}
	
	@Override
	public void actionPerformed(ActionEvent actionEvent) {
		
		
		Object source = actionEvent.getSource();
		logger.debug("Action performed from [{}]", source);
		
		if(source instanceof JButton) {
			String command = ((JButton) source).getActionCommand();
			if(command.equals("submit")) {
				
				String input = textArea.getText();
				logger.debug("Text from text field: [{}]", input);
				
				EncodingType type = (EncodingType) comboBox.getSelectedItem();
				
				encoder = FileEncoderFactory.getEncoder(type);
				
				logger.debug("Encoding...");
				encoder.encode(input);
				
			} else if(command.equals("inspect")) {
				logger.debug("Inspecting file");
				
				decoder = new FileDecoder();
				JFrame frame = (JFrame) SwingUtilities.getRoot((JButton) source);
				
				FileDialog dialog = new FileDialog(frame, "Choose file", FileDialog.LOAD);
				dialog.setVisible(true);
				String readPath = dialog.getDirectory() + dialog.getFile();
				
				logger.debug("Parent container [{}].", frame);
				logger.info("Chose file from [{}].", readPath);
				Charset charset = decoder.decode(readPath);
				
				JOptionPane.showMessageDialog(frame, charset +
					    " charset encoding.");
			}
			

		}
	}

	
	

}
